package com.dingpeikeji.quickdeer.modules.pay.web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dingpeikeji.quickdeer.core.common.utils.CacheUtils;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.realsche.service.TRealscheService;
import com.dingpeikeji.quickdeer.mobile.service.TripCounselorService;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ShareRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.ShareProductService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.tencent.common.Signature;

@Controller
@RequestMapping("weixin")
public class WeixinCommonPageController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private FRealscheService fRealscheService;
	@Autowired
	private TRealscheService tRealscheService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private ShareProductService shareProductService;
	@Autowired
	private TripCounselorService tripCounselorService;

	/**
	 * 微信支付成功后回调通知
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("notify")
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.debug("微信支付回调通知");
		BufferedReader bis = new java.io.BufferedReader(new InputStreamReader(request.getInputStream()));
		String line = null;
		String result = "";
		try {
			while ((line = bis.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bis.close();
		}
		logger.debug("微信回调接口接收到的报文：\n{}", result);
		Document doc = DocumentHelper.parseText(result);
		Element root = doc.getRootElement();
		
		String return_code = root.elementTextTrim("return_code");
		String return_msg = root.elementTextTrim("return_msg");
		logger.debug("回调返回的状态信息：\nreturn_code={}\nreturn_msg={}",return_code, return_msg);
		//return_code=SUCCESS
		//return_msg=null
		if(StringUtils.isNoneBlank(return_code) && "SUCCESS".equals(return_code)) {
			// 获取签名
			String sign = root.elementTextTrim("sign");
			logger.debug("微信返回的签名：sign={}", sign);//微信返回的签名：sign=88415572D51F7D84C9B436C0D72F329D
			String mysign = Signature.getSignFromResponseString(result);
			logger.debug("服务器生成的签名：sign={}", mysign);//服务器生成的签名：sign=00E151C2D4A8D07F7B6C50086A1BE575
			if(sign.equals(mysign)){ // 校验通过
				String out_trade_no = root.elementTextTrim("out_trade_no");
				String transaction_id = root.elementTextTrim("transaction_id");
				String total_fee = root.elementTextTrim("total_fee");
				String openid = root.elementTextTrim("openid");
				
				Map<String,Object> proResult = fRealscheService.proConfirmPay(Integer.parseInt(out_trade_no), Double.parseDouble(total_fee), transaction_id, openid, TOrders.PAY_WAY_WXPAY);
				Integer returnflag = (Integer)proResult.get("returnflag");
				logger.debug("回调返回的状态信息=======：\nreturnflag={}",returnflag);
				logger.debug("回调返回的状态信息=======：\nout_trade_no={}",out_trade_no);
				if(returnflag != null && returnflag == 0) {
					// 发短信给用户
					Sms sendSms = tOrdersService.composeSms(out_trade_no);
					if (sendSms != null){
						SmsApi.sendSms(sendSms);
					}
					//更改订单支付方式
					fRealscheService.updateOrderById(TOrders.PAY_WAY_WXPAY,out_trade_no);
					//拼车创建人支付成功,修改拼车产品,让该产品显示在AA拼车列表
					TOrders tOrders = tOrdersService.get(out_trade_no);
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
					if (StringUtils.isNotEmpty(tOrders.getShareid())) {
						//修改产品状态
						ShareRentproduct shareRentproduct = shareProductService.getInfo(tOrders.getShareid());
						shareProductService.updateStatus(tOrders.getShareid(),"1");
						//修改shareproduct表中的已购买数量
						int alreadySell = tOrders.getPaycount()+shareRentproduct.getCurrentsell();
						shareProductService.updateSellAmount(tOrders.getShareid(),alreadySell+"");
						//AA拼车,人数达到要求,并且在截至日期之前,发送短信给全体订单用户,并修改拼车产品生效
						if (new Date().before(shareRentproduct.getEnddate())&&shareRentproduct.getMinamount().equals(alreadySell+"")) {
							int rs = shareProductService.updateSuccess(shareRentproduct.getSid());
							if((alreadySell+"").equals(shareRentproduct.getMaxamount())){
								shareProductService.updateStatus(tOrders.getShareid(),"0");
							}
							if (rs>0) {
								//处理整包车订单
								tRealscheService.updateStateForShare(tOrders.getRealscheid());
								//更新为未调度
								tRealscheService.updateDispstatusForShare(tOrders.getRealscheid());
								//发送短信给车队管理者
								Sms send = new Sms();
								//查询车队管理者
								send.setMobile(tOrders.getOffice().getOperatortel());
								send.setContent("您有一个新订单需要处理"+
										"，订单名:"+tOrders.getOrdername()+","+tOrders.getCartype().getTypename()+
										tOrders.getPurchasenum()+"辆，发车时间："+df.format(tOrders.getDepartdate())
										+"。为保护您和订车人的合法权益，请及时安排调度。如有任何疑问，欢迎咨询客服4009287733");
								SmsApi.sendSms(send);
								//发送短信给所有用户
								Sms sendUser = new Sms();
								//根据shareid查询购买拼车产品的手机
								List<String> telList = tOrdersService.getOrderTelByShareId(shareRentproduct.getSid());
								for (String tel : telList) {
									sendUser.setContent("【霞客约车】拼友你好，"+tOrders.getOrdername()+"已拼成功，订单不可退款。"
											+ "请于出行当天至少提前20分钟到达上车地点("+tOrders.getBoardaddr()+")，行车具体车牌号及司机信息将于出行前1-2天发送给本手机，若未收到请及时联系客服400－928－7733。");
									sendUser.setMobile(tel);
									SmsApi.sendSms(sendUser);
								}
							}
						}
					}
					CacheUtils.put("feedback_order_id"+Integer.parseInt(out_trade_no), "success");
					if(tOrdersService.get(out_trade_no).getOrdertype().equals("9")){
						tripCounselorService.updateTripState(out_trade_no,"1");
					}
					logger.debug("回调返回的状态信息!!!!!!!!!!!!!!!：\nfeedback_order_id={}",Integer.parseInt(out_trade_no));
					// 通知微信该回调已经处理
					response.setHeader("Content-Type", "text/xml");
					response.getWriter().append("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
				}
			}
		}
	}
}
